<template>
	<view>
		<shopping v-if="showpage === 'shopping'" :productList="products" :userList="userList" :category="category" :senderUserId="senderUserId"></shopping>
		<shopMain v-if="showpage === 'shopMain'" :products="products" :userList="userList" @shopDetail="shopDetail"></shopMain>
		<!-- <shopFootBar @selecMenu="selecMenu"></shopFootBar> -->
		<!-- 
		<movable-area
			:style="{
				width: windowWidth + 'px',
				height: windowHeight + 'px', // 修正拼写错误
				position: 'fixed', // 固定在窗口，不随滚动移动
				top: 0,
				left: 0,
				zIndex: 9999, // 确保在最上层
				pointerEvents: 'none' // 允许点击穿透到下层内容
			}"
		>
			<movable-view direction="all" style="pointer-events: auto" x="500" y="800">
			
				<RightBar :type="'shop'" :cart-show="true" :friend-show="true" :bottom="180 + 'rpx'"></RightBar>
			</movable-view>
		</movable-area>
		 -->
	</view>
</template>

<script>
import shopFootBar from '../../components/shopFootBar.vue';
import shopping from '@/pages/shopping/shopping.vue';
import shopMain from '../shopMain/shopMain.vue';
import { fileIdToUrl } from '@/utils/fileIdToUrl.js';
const db = uniCloud.databaseForJQL();
const order = uniCloud.importObject('order',{customUI:true});
import RightBar from '../../components/RightBar.vue';
export default {
	components: {
		shopping,
		shopMain,
		shopFootBar,
		RightBar
	},
	onShow() {
		uni.$on('searchResult', (products) => {
			console.log('接收搜索结果:', products);
			// 处理结果（如更新列表、刷新数据）
			this.searchResult(products);
		});
	},

	// 3. 上一页：页面卸载时移除监听（避免内存泄漏）
	onUnload() {
		uni.$off('searchResult');
	},
	onLoad() {
		// this.getGoodlist();
		// this.getCategory();
		this.getsystemInfo();
		this.initData();
		this.getCategory();
		this.getUsedAddress();
	},
	data() {
		return {
			showpage: 'shopMain',
			userList: [],
			products: [],
			category: [],
			senderUserId: '',
			windowHeight: 0,
			windowWidth: 0
		};
	},

	methods: {
		getsystemInfo() {
			const res = this.$store.state.msg.systemInfo;
			this.windowHeight = res.windowHeight;
			this.windowWidth = res.windowWidth;
		},
		async searchResult(products) {
			const userIds = [...new Set(products.map((item) => item.senderUserId))];

			// 4. 批量获取用户信息
			const userRes = await db
				.collection('linli-user')
				.where({ userId: db.command.in(userIds) })
				.field({ nicPic: true, nicName: true, userId: true }) // 必须包含userId用于映射
				.get();

			// 5. 创建用户信息映射表（userId -> 用户信息）
			const userMap = new Map();
			userRes.data.forEach((user) => {
				userMap.set(user.userId, {
					nicName: user.nicName,
					nicPic: user.nicPic // 转换用户头像URL
				});
			});
			// 6. 将用户信息映射到商品数据中
			const productsWithUser = products.map((product) => ({
				...product,
				// 添加用户信息，找不到时使用默认值
				userInfo: userMap.get(product.senderUserId) || {
					nicName: '未知用户',
					nicPic: ''
				}
			}));
			this.userList = Array.from(userMap).map(([userId, userInfo]) => ({
				userId: userId, // 保留用户ID（可选，用于标识用户）
				...userInfo // 展开用户信息（nicName、nicPic）
			}));
			// 7. 更新数据
			this.products = productsWithUser;
		},
		selecMenu(word) {
			this.showpage = word;
		},
		async initData() {
			try {
				const res = await order.getProduct({});
			
				if (res.success) {
					this.products = res.products
					this.userList = res.senderUser;
				} else {
					console.log('获取商品信息失败');
				}
			} catch (e) {
				console.log(e);
			}
		},
		processCategories() {
			// 1. 创建分类映射对象
			const categoryMap = {};

			// 2. 遍历商品数据，统计分类信息
			this.products.forEach((product) => {
				const mainCategory = product.categorize || '未分类';
				const subCategory = product.subCategorize || '未分类';

				// 如果大类不存在，初始化
				if (!categoryMap[mainCategory]) {
					categoryMap[mainCategory] = {
						name: mainCategory,
						totalCount: 0, // 大类商品总数
						subcategories: {} // 小类映射 { 小类名称: { name, count } }
					};
				}

				// 如果小类不存在，初始化
				if (!categoryMap[mainCategory].subcategories[subCategory]) {
					categoryMap[mainCategory].subcategories[subCategory] = {
						name: subCategory,
						count: 0
					};
				}

				// 统计数量
				categoryMap[mainCategory].totalCount++;
				categoryMap[mainCategory].subcategories[subCategory].count++;
			});

			// 3. 转换为数组格式，方便页面渲染
			this.category = Object.values(categoryMap).map((main) => ({
				...main,
				// 将小类对象转换为数组，并按数量降序排列
				subcategories: Object.values(main.subcategories).sort((a, b) => b.count - a.count)
			}));

			// 4. 按大类商品总数降序排列
			this.category.sort((a, b) => b.totalCount - a.totalCount);

			this.loading = false;
		},
	async getCategory() {
	    try {
	        this.loading = true;
	
	        // 1. 安全获取 userId
	        const globalState = this.$store.state || {};
	        const userInfo = globalState.msg?.user || {};
	        const userUserId = userInfo.userId; // 用户自己的 userId
	        const defaultUserId = 'system';   // 默认的 userId
	
	        let finalResult = []; // 用于存储最终查询结果
	
	        // 2. 第一步：使用用户自己的 userId 进行查询
	        if (userUserId) {
	            console.log(`正在使用用户 userId ${userUserId} 查询分类...`);
	            const userRes = await db
	                .collection('category')
	                .where({ userId: userUserId })
	                .get();
	             console.log("5555555",userRes);
	            // 检查查询结果是否有效且不为空
	            if (userRes && Array.isArray(userRes.data) && userRes.data.length > 0) {
	                finalResult = userRes.data;
	                console.log(`用户 userId ${userUserId} 查询成功，结果数：${finalResult.length}`);
	            } else {
	                console.warn(`用户 userId ${userUserId} 未查询到分类数据，将使用默认 userId ${defaultUserId} 重试...`);
	            }
	        } else {
	            console.warn('未获取到用户 userId，将直接使用默认 userId 查询...');
	        }
	
	        // 3. 第二步：如果第一步结果为空，则使用默认 userId 进行查询
	        if (finalResult.length === 0) {
	           
	            const defaultRes = await db
	                .collection('category')
	                .where({ userId: defaultUserId })
	                .get();
	
	            if (defaultRes && Array.isArray(defaultRes.data)) {
	                finalResult = defaultRes.data;
	               
	            } else {
	                console.warn(`默认 userId ${defaultUserId} 也未查询到分类数据。`);
	            }
	        }
	
	        // 4. 处理最终结果并赋值
	        if (finalResult.length > 0) {
	            this.category = finalResult[0].category;
	        } else {
	            this.category = []; // 如果两次查询都为空，也给一个空数组兜底
	        }
	
	    } catch (e) {
	        // 5. 错误处理
	        console.error('获取分类失败：', {
	            error: e,
	            userId: this.$store.state?.msg?.user?.userId
	        });
	        this.category = [];
	    } finally {
	        // 6. 确保加载状态关闭
	        this.loading = false;
	    }
	},
		shopDetail(id) {
			this.senderUserId = id;
			this.showpage = 'shopping';
		},
		async getUsedAddress() {
			var address = [];
			try {
				const res = await db.collection('orderAddress').where({ userId: this.$store.state.msg.user.userId }).orderBy('createTime', 'desc').get();

				address = res.data || [];

				this.$store.commit('cart/SET_orderAddress', address);
			} catch (e) {
				uni.showToast({ title: '地址加载失败', icon: 'none' });
			}
		}
	}
};
</script>

<style></style>
